<template>
  <div style="padding-left: 20px">
    <el-row>
      <el-col :span="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="75px">
          <el-form-item label="请选择子设备:" label-width="120px" v-if="isSubDev">
            <el-select v-model="queryParams.slaveId" placeholder="请选择子设备" @change="selectSlave">
              <el-option v-for="slave in slaveList" :key="slave.deviceId"
                :label="`${slave.deviceName} (${slave.serialNumber})`" :value="slave.deviceId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker v-model="daterangeTime" size="small" style="width: 240px" value-format="yyyy-MM-dd"
              type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="getListHistory(false)">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="24">
        <el-card shadow="hover" :body-style="{ padding: '10px', overflow: 'auto' }" v-loading="loading">
          <el-table :data="tableData" style="width: 100%" stripe border size="small" :row-key="rowKey" :key="tableKey"
            :default-sort="{ prop: 'time', order: 'descending' }">
            <el-table-column label="时间" prop="time" width="200" fixed="left" sortable />
            <el-table-column v-for="col in currentProperties" :key="col.id" :prop="col.id" :label="col.name"
              width="180">
              <template slot-scope="scope">
                {{ scope.row[col.id] || '—' }}
              </template>
            </el-table-column>
          </el-table>

          <div style="margin-top: 15px; text-align: center">
            <el-pagination background layout="prev, pager, next" :page-size="pageSize" :current-page="pageNum"
              @current-change="handlePageChange" :total="total" />
          </div>

          <div v-if="!loading && tableData.length === 0" style="text-align: center; padding: 20px">
            没有找到相关数据
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listHistory } from '@/api/iot/deviceLog';

export default {
  name: 'device-statistic',
  props: {
    device: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      actualSerialNumber: '', // 当前选中的设备编号
      slaveList: [],          // 子设备列表（如果不是子设备）
      loading: false,
      tableData: [],
      rawTableData: {},
      pageNum: 1,
      pageSize: 20,
      total: 0,
      tableHeight: 400,
      queryParams: {
        identity: '',
        serialNumber: '',
        beginTime: '',
        endTime: '',
        slaveId: undefined,
      },
      daterangeTime: (() => {
        const today = new Date();
        const yyyy = today.getFullYear();
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const dd = String(today.getDate()).padStart(2, '0');
        const dateStr = `${yyyy}-${mm}-${dd}`;
        return [dateStr, dateStr];
      })(),
      deviceInfo: {},
      currentProperties: [],
      allProperties: [],
      slaveList: [],
      isSubDev: false,
      tableKey: Date.now(),
    };
  },
  watch: {
    device: {
      handler(newVal) {
        this.deviceInfo = newVal;

        if (this.deviceInfo && this.deviceInfo.deviceId != 0) {
          this.isSubDev = this.deviceInfo.subDeviceList && this.deviceInfo.subDeviceList.length > 0;
          this.queryParams.slaveId = this.deviceInfo.slaveId;
          this.slaveList = newVal.subDeviceList;

          if (this.isSubDev && this.slaveList.length > 0) {
            this.queryParams.slaveId = this.slaveList[0].deviceId;
          }
          // 处理设备数据
          if (this.isSubDev) {

            const slaveId = this.queryParams.slaveId || (this.slaveList[0]?.deviceId); // 若没有则用第一个
            const slave = this.deviceInfo.subDeviceList.find(d => d.deviceId === slaveId);
            //this.staticList = this.deviceInfo.cacheThingsModel['properties'].filter(item => item.tempSlaveId === this.queryParams.slaveId);
            this.staticList = slave.thingsModelValue
          } else {
            this.staticList = this.deviceInfo.staticList;
          }
          // 获取监测数据
          // this.getListHistory();
          this.processDeviceInfo()
        }

      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    processDeviceInfo() {
      this.isSubDev = this.deviceInfo.subDeviceList && this.deviceInfo.subDeviceList.length > 0;
      this.slaveList = this.deviceInfo.subDeviceList || [];
      this.allProperties = this.deviceInfo.staticList || [];
      console.log(this.allProperties)
      if (this.isSubDev) this.selectSlave();
      else this.setCurrentProperties();

      //this.getListHistory(false);
    },
    setCurrentProperties() {
      this.currentProperties = this.allProperties.map(p => ({
        id: p.id,
        name: p.name || p.id,
      }));
    },
    selectSlave() {
      const slaveId = this.queryParams.slaveId || (this.slaveList[0] && this.slaveList[0].deviceId);
      const slave = this.slaveList.find(s => s.deviceId === slaveId);
      this.queryParams.slaveId = slaveId;
      this.queryParams.serialNumber = slave?.serialNumber || this.deviceInfo.serialNumber;

      let slaveProps = [];
      try {
        slaveProps = JSON.parse(slave.thingsModelValue || '[]');
      } catch (e) { }
      this.allProperties = [...this.deviceInfo.staticList, ...slaveProps];
      this.setCurrentProperties();
    },
    normalizeTime(t) {
      try {
        const date = typeof t === 'number' ? new Date(t) : new Date(t.replace(' ', 'T'));
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
      } catch (e) {
        return t;
      }
    },
    getListHistory(reset = false) {
      if (reset) {
        this.pageNum = 1;
        this.tableData = [];
        this.rawTableData = {};
        this.total = 0;
      }
      if (!this.isSubDev) {
        this.queryParams.serialNumber = this.deviceInfo.serialNumber
      }

      this.loading = true;

      const identityList = this.currentProperties.map(p => p.id);
      this.queryParams.identity = identityList.join(',');

      if (this.daterangeTime?.length === 2) {
        this.queryParams.beginTime = `${this.daterangeTime[0]} 00:00:00`;
        this.queryParams.endTime = `${this.daterangeTime[1]} 23:59:59`;
      }

      this.queryParams.pageNum = this.pageNum;
      this.queryParams.pageSize = this.pageSize;

      listHistory(this.queryParams).then(res => {
        if (res.code === 200 && res.data) {
          const newData = res.data.data || {};
          this.total = res.data.totalTimestamps || 0;


          // 整理数据
          this.rawTableData = newData;
          this.processDataInChunks();
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error("请求失败，请重试");
      });
    },
    processDataInChunks() {
      const allTimes = new Set();
      for (const key in this.rawTableData) {
        const points = this.rawTableData[key] || [];
        for (const point of points) {
          if (point.time) allTimes.add(this.normalizeTime(point.time));
        }
      }
      const sortedTimes = Array.from(allTimes).sort().reverse(); // 时间倒序
      const allRows = sortedTimes.map(time => ({ time }));

      for (const row of allRows) {
        for (const prop of this.currentProperties) {
          const list = this.rawTableData[prop.id] || [];
          const match = list.find(p => this.normalizeTime(p.time) === row.time);
          row[prop.id] = match ? match.value : '—';
        }
      }

      this.tableData = allRows;
      this.tableKey = Date.now();
    },
    handlePageChange(newPage) {
      this.pageNum = newPage;
      this.getListHistory(false);
    },
    rowKey(row) {
      return row.time + '_' + this.tableKey;
    }
  }
};
</script>

<style scoped>
.el-card {
  max-height: 80vh;
  overflow: hidden;
}
</style>
